package com.naja.cdc.develop.handler;

import com.alibaba.fastjson.JSONObject;
import com.naja.cdc.framework.data.DebeziumData;
import com.naja.cdc.framework.handler.es.DebeziumBaseObjectsEsHandler;
import io.debezium.data.Envelope;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.xcontent.XContentBuilder;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;

/**
 * 拓展处理器示例
 */
@Slf4j
//@Component
public class DemoHandler extends DebeziumBaseObjectsEsHandler {

    @Override
    protected void customScriptParams(DebeziumData debeziumData, HashMap<String, Object> scriptParams) {
        String table = debeziumData.getTable();
        JSONObject newData = debeziumData.getNewData();
        Envelope.Operation operation = debeziumData.getOperation();
        Map<String, Object> filedValueMap = (Map<String, Object>) scriptParams.get("filedValue");
        Set<String> nameSplitSet = new HashSet<>();
        filedValueMap.put("carrierNameSplit", nameSplitSet);
        String carrierName = filedValueMap.get("carrierName").toString();
        if (!StringUtils.isEmpty(carrierName) && carrierName.length() <= 4) {
            char[] carrierNameChars = carrierName.toCharArray();
            for (int i = 0; i < carrierNameChars.length; i++) {
                String tmp = carrierNameChars[i] + "";
                nameSplitSet.add(tmp);
                for (int j = i + 1; j < carrierNameChars.length; j++) {
                    tmp += carrierNameChars[j];
                    nameSplitSet.add(tmp);
                }
            }
        } else {
            nameSplitSet.add(carrierName);
        }

        String tag = String.join(" ", Arrays.asList(
                "carrierOrderNum:" + newData.getString("carrier_order_num"),
                "collectionMode:" + newData.getInteger("collection_mode")
        ));
        filedValueMap.put("logicalTag", tag);
    }

    @Override
    protected void customObjectFiledXContentBuilder(DebeziumData debeziumData, XContentBuilder objectFiledXContentBuilder) throws IOException {
        String table = debeziumData.getTable();
        JSONObject newData = debeziumData.getNewData();
        if (table.equals("t_deliver_order_contact") || table.equals("t_deliver_order_receiver")
                || table.equals("t_receive_order_contact") || table.equals("t_receive_order_receiver")) {
            objectFiledXContentBuilder.field("pccsAddr",
                    newData.getString("province") +
                            newData.getString("city") +
                            newData.getString("county") +
                            newData.getString("street") +
                            newData.getString("addr"));
        } else if (table.equals("t_deliver_order")) {
            objectFiledXContentBuilder.field("ownerCompanyOrgIdConcatCreateBy", newData.getLong("owner_company_org_id") + "-" + newData.getLong("create_by"));
        }
    }

}
